﻿using DistributedVisionRunner.Module.Models;
using System;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Markup;

namespace DistributedVisionRunner.Module.Converters
{
    public class ImageLayoutParameterToItemsPanelTemplateConverter : MarkupExtension, IValueConverter
    {
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var placement = (ImageLayoutParameter)value;
            return GetItemsPanelTemplate(new PlacementParameter() { ItemsPerRow = placement.ImagesPerRow, PlacementMethod = placement.PlacementMethod });

        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Binding.DoNothing;
        }


        private static ItemsPanelTemplate GetItemsPanelTemplate(PlacementParameter parameter)
        {
            string xaml = null;
            if (parameter.PlacementMethod == ItemPlacementMethod.HorizontalStack)
            {
                xaml = @"<ItemsPanelTemplate   xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
                <StackPanel Orientation='Horizontal'/>
                    </ItemsPanelTemplate>";
            }
            else if (parameter.PlacementMethod == ItemPlacementMethod.VerticalStack)
            {
                xaml = @"<ItemsPanelTemplate   xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
                <StackPanel Orientation='Vertical'/>
                    </ItemsPanelTemplate>";
            }
            else if (parameter.PlacementMethod == ItemPlacementMethod.Wrap)
            {
                xaml = @"<ItemsPanelTemplate   xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
                <WrapPanel/>
                    </ItemsPanelTemplate>";
            }
            else if (parameter.PlacementMethod == ItemPlacementMethod.UniformGrid)
            {
                xaml =
                    $@"<ItemsPanelTemplate   xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
                <UniformGrid Columns='{parameter.ItemsPerRow}'/>
                    </ItemsPanelTemplate>";
            }


            return XamlReader.Parse(xaml) as ItemsPanelTemplate;
        }
    }
}